package com.tsu.mall.admin.controller;


import com.tsu.mall.common.util.ImageUtil;
import com.tsu.mall.admin.util.RequestUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;


@Controller
@RequestMapping("/")
public class ImageController {

	@GetMapping("/image")
	protected void catcherPage(HttpServletResponse response) throws IOException {
		//返回值类型为image图片
		response.setContentType("image/jepg");
		//禁止图片缓存
		response.setHeader("parama", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		ServletOutputStream sos=response.getOutputStream();
		//随机生成一个四位字符串
		String str=randomString(4);
		ImageIO.write(ImageUtil.image(str), "JPEG", sos);//流写出图像
	   //将验证码存入session
		RequestUtil.getSession().setAttribute("captcha", str);
		//释放资源
		sos.flush();
		sos.close();
	}
	//生成验证码,随机生成字符串，可指定长度
	public String randomString(int length) {
		Random random=new Random();
		StringBuffer sb=new StringBuffer();
		for(int i=1;i<=length;i++) {
			int number=random.nextInt(4);//随机生成一个[0,4)的数
			long result=0;
			switch(number) {
			case 0://生成一个小写英文字母
				result=Math.round(Math.random()*25+65);
				sb.append((char)result);
				break;
			case 1://生成一个大写英文字母
				result=Math.round(Math.random()*25+97);
				sb.append((char)result);
				break;
				//生成一个0~9的数字
			case 2:
				case 3:
				sb.append(new Random().nextInt(10));
				break;
			}
		}
		return sb.toString();
	}
}
